package helper

import (
	"errors"
	"github.com/slclub/go-tips/json"
)

type Jsonl struct {
}

func (self *Jsonl) Unmarsharl(datab []byte, target any) error {
	tar_arr, ok := target.(*[]any)
	if !ok {
		return errors.New("JSONL.TARGET.NOT_ARRAY")
	}
	bs := []byte{}
	for _, v := range datab {
		if v != '\n' {
			bs = append(bs, v)
			continue
		}
		tar_d := map[string]any{}
		err := json.Unmarshal(bs, &tar_d)
		bs = bs[:0]
		if err != nil {
			continue
		}
		*tar_arr = append(*tar_arr, tar_d)
	}
	return nil
}

func (self *Jsonl) MapReadline(datab []byte, mf func(b []byte) bool) error {
	bs := []byte{}
	for _, v := range datab {
		if v != '\n' {
			bs = append(bs, v)
			continue
		}
		ok := mf(bs)
		if !ok {
			break
		}
		bs = bs[:0]
	}
	return nil
}
